<template>
  <div>
    <el-dialog
      v-model="centerDialogVisible"
      title="上传文件"
      width="500"
      center
      @close="HandlerClose"
      :close-on-press-escape="isLoading ? false : true"
      :close-on-click-modal="isLoading ? false : true"
    >
      <el-upload
        v-loading="isLoading"
        class="upload-demo"
        drag
        action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
        :auto-upload="false"
        ref="upload"
        :on-change="ChangeHandler"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">可拖拽文件上传或者 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            大于1GB的文件请使用<em>ftp</em>上传或者压缩后进行尝试上传
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="HandlerClose">取消</el-button>
          <el-button type="primary" @click="AddFiles"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { uploadFileAPI } from "@/api/file";
import { ElMessage } from "element-plus";
import { ref } from "vue";
let upload = ref(null);
let centerDialogVisible = defineModel();
let parentId = defineModel("parentId");
let list = defineModel("list");
let files = ref("");
let isLoading = ref(false);
const emits = defineEmits(["getUploadList"]);
const HandlerClose = () => {
  centerDialogVisible.value = false;
  upload.value.clearFiles();
  isLoading.value = false;
  files.value = ''
};
const ChangeHandler = (file) => {
  console.log(file);
  if (file.size > 1024 * 1024 * 1024) {
    upload.value.clearFiles();
    ElMessage.error("文件大小超过1GB，请使用ftp上传或者压缩后进行尝试上传");
  } else {
    files.value = file.raw;
  }
};
const AddFiles = async () => {
  if (!files.value) {
    ElMessage.error("请选择文件");
    return;
  }
  let isReturn = false;
  list.value.forEach((item) => {
    if (item.fileName == files.value.name) {
      isReturn = true;
    }
  });
  if (isReturn) {
    ElMessage.error("文件已存在，请重新选择文件");
    return;
  }
  isLoading.value = true;
  let formData = new FormData();
  formData.append("file", files.value);
  let result = await uploadFileAPI(parentId.value, formData);
  isLoading.value = false;
  if (result.code === 200) {
    ElMessage.success("上传成功");

    HandlerClose();
    emits("getUploadList", parentId.value);
  }
};
</script>

<style lang="scss" scoped></style>
